/*
 * sortmoves.c
 *
 *  Created on: Apr 18, 2013
 *      Author: locpx
 */
#include "extglobals.h"
#include "move.h"

void selectmove(int ply, int i, int depth, BOOL followpv)
{
	int j, k;
	unsigned int best;
	MOVE temp;

	// re-orders the move list so that the best move is selected as the next move to try.
	if (followpv && depth > 1)
	{
		for (j = i + 1; j < board.moveBufLen[ply+1]; j++)
		{
			if (board.moveBuffer[j].moveInt == board.lastPV[ply].moveInt)
			{
				temp.moveInt = board.moveBuffer[j].moveInt;
				board.moveBuffer[j].moveInt = board.moveBuffer[i].moveInt;
				board.moveBuffer[i].moveInt = temp.moveInt;
				return;
			}
		}
	}

	if (board.nextMove)
	{
		best = board.blackHeuristics[getFrom(board.moveBuffer[i])][getTosq(board.moveBuffer[i])];
		j = i;
		for (k = i + 1; k < board.moveBufLen[ply+1]; k++)
		{
			if (board.blackHeuristics[getFrom(board.moveBuffer[k])][getTosq(board.moveBuffer[k])] > best)
			{
				best = board.blackHeuristics[getFrom(board.moveBuffer[k])][getTosq(board.moveBuffer[k])];
				j = k;
			}
		}
		if (j > i)
		{
			temp.moveInt = board.moveBuffer[j].moveInt;
			board.moveBuffer[j].moveInt = board.moveBuffer[i].moveInt;
			board.moveBuffer[i].moveInt = temp.moveInt;
		}
	}
	else
	{
		best = board.whiteHeuristics[getFrom(board.moveBuffer[i])][getTosq(board.moveBuffer[i])];
		j = i;
		for (k = i + 1; k < board.moveBufLen[ply+1]; k++)
		{
			if (board.whiteHeuristics[getFrom(board.moveBuffer[k])][getTosq(board.moveBuffer[k])] > best)
			{
				best = board.whiteHeuristics[getFrom(board.moveBuffer[k])][getTosq(board.moveBuffer[k])];
				j = k;
			}
		}
		if (j > i)
		{
			temp.moveInt = board.moveBuffer[j].moveInt;
			board.moveBuffer[j].moveInt = board.moveBuffer[i].moveInt;
			board.moveBuffer[i].moveInt = temp.moveInt;
		}
	}

	return;
}
